<template>
  <div class="message-renderer">
    <div class="message-text" v-html="renderedContent"></div>

    <!-- 图片预览模态框 -->
    <div
      v-if="showImageModal"
      class="fixed inset-0 bg-black/80 flex items-center justify-center z-50"
      @click.self="showImageModal = false"
    >
      <button
        @click="showImageModal = false"
        class="absolute top-4 right-4 text-white text-2xl"
      >
        <i class="fa fa-times"></i>
      </button>
      <img
        :src="modalImageSrc"
        alt="预览图片"
        class="max-w-[90%] max-h-[90vh] object-contain"
      />
    </div>
  </div>
</template>

<script setup lang="tsx">
import { defineComponent, ref, onMounted } from "vue";
import MarkdownIt from "markdown-it";
import { PreRender } from "./index";
import hljs from "highlight.js";
import ClipboardJS from "clipboard";
const props = defineProps({
  content: {
    type: String,
    required: true,
  },
  type: {
    type: String,
    default: "assistant",
  },
});

const getStrTool = (highlighted) => {
  // 添加复制按钮
  const codeId = `code-${Date.now()}`; // 唯一ID避免冲突
  return `
      <div class="code-block">
       <button class="copy-btn"
       data-id="${codeId}"
       data-clipboard-target="#${codeId}">复制</button>
        <pre><code class="hljs" id="${codeId}">${highlighted}</code></pre>
       
      </div>
    `;
};
// 初始化 Markdown 解析器
const md = MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  highlight: function (str, lang) {
    // 处理 Vue 语言：使用 HTML 高亮
    if (lang && lang.toLowerCase() === "vue") {
      try {
        return getStrTool(
          hljs.highlight(str, { language: "html", ignoreIllegals: true }).value
        );
      } catch (__) {}
    }

    if (lang && hljs.getLanguage(lang)) {
      try {
        return getStrTool(
          hljs.highlight(str, { language: lang, ignoreIllegals: true }).value
        );
      } catch (__) {}
    }

    return getStrTool(md.utils.escapeHtml(str));
  },
});
// 自定义代码块渲染器
// 自定义 fence 渲染规则
md.renderer.rules.fence = (tokens, idx, options, env, self) => {
  const token = tokens[idx];
  const code = token.content.trim();
   const lang = token.info || '';

            // 处理 Vue 语言：使用 HTML 高亮
    if (lang && lang.toLowerCase() === "vue") {
      try {
        return getStrTool(
          hljs.highlight(code, { language: "html", ignoreIllegals: true }).value
        );
      } catch (__) {}
    }

    if (lang && hljs.getLanguage(lang)) {
      try {
        return getStrTool(
          hljs.highlight(code, { language: lang, ignoreIllegals: true }).value
        );
      } catch (__) {}
    }

    return getStrTool(md.utils.escapeHtml(code));
};

const renderedContent = ref("");
const showImageModal = ref(false);
const modalImageSrc = ref("");
function initClipboard() {
  new ClipboardJS(".copy-btn", {
    text: (trigger: any) => {
      // 获取相邻代码块的内容
      const id = trigger.dataset.id;
      console.log(
        "document.getElementById(id) :>> ",
        document.getElementById(id)
      );
      return document.getElementById(id).innerText;
    },
  }).on("success", (e) => {
    e.trigger.textContent = "已复制";
    setTimeout(() => (e.trigger.textContent = "复制"), 3000); // 3秒后恢复
    e.clearSelection(); // 清除选中状态
  });
}
// 渲染 Markdown
const renderMarkdown = () => {
  // 渲染 Markdown
  let html = md.render(props.content);

  renderedContent.value = html;

  // 为复制按钮添加事件
  setTimeout(() => {
    initClipboard();

    // 为图片添加点击事件
    document.querySelectorAll(".markdown-content img").forEach((img) => {
      img.addEventListener("click", function () {
        modalImageSrc.value = this.src;
        showImageModal.value = true;
      });
    });
  }, 0);
};

// 初始渲染
onMounted(() => {
  renderMarkdown();
});
</script>

<style lang="scss" >
.message-renderer {
  .message-text {
    p {
      line-height: 1.5;
    }
  }
  /* 代码块容器 */
  .code-block {
    position: relative;
    padding: 10px;
  }

  /* 复制按钮 */
  .copy-btn {
    position: absolute;
    top: 4px;
    right: 8px;
    background: #525252;
    color: #fff;
    border: none;
    padding: 4px 8px;
    border-radius: 4px;

    cursor: pointer;
    opacity: 0;
    transition: opacity 0.3s;
  }

  .code-block:hover .copy-btn {
    opacity: 1; /* 悬停时显示 */
  }
}
</style>  